<template>
    <div class="container">
        <div class="breadcrumb-container">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <router-link to="/user/location">党建地点</router-link>
                </el-breadcrumb-item>
                <el-breadcrumb-item>党建地点详细信息</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <el-card class="main-card">
            <div class="content">
                <div class="location-detail">
                    <el-card class="image-card">
                        <img
                            v-if="locationDetails.photo"
                            :src="locationDetails.photo"
                            alt="Location Image"
                            class="location-image"
                        />
                    </el-card>

                    <div class="location-info">
                        <h2>{{ locationDetails.name }}</h2>
                        <p><strong>预约人数:</strong> {{ locationDetails.balance }}</p>
                        <p><strong>地址:</strong> {{ locationDetails.address }}</p>
                        <p><strong>类型:</strong> {{ locationDetails.type }}</p>
                    </div>
                </div>

                <div class="recommendations">
                    <h3>系统推荐</h3>
                    <el-row :gutter="20" class="recommendation-list">
                        <el-col
                            v-for="location in recommendedLocations"
                            :key="location.id"
                            :span="24"
                            class="recommendation-item"
                            @click="navTo(`/user/location/detail?name=${location.name}&id=${location.id}`)"
                        >
                            <div class="recommended-content">
                                <img
                                    :src="location.photo"
                                    alt="推荐地点"
                                    class="recommendation-image"
                                />
                                <div class="recommendation-name">{{ location.name }}</div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </div>

            <!-- 预约按钮 -->
            <div class="booking-section">
                <el-button type="primary" @click="bookLocation">预约</el-button>
            </div>
            <!-- 预约对话框 -->
            <el-dialog title="选择预约时间" v-model="showDialog" width="50%">
                <el-date-picker
                    v-model="appointmentTime"
                    type="datetime"
                    placeholder="选择日期时间"
                />
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmBooking">确定</el-button>
                </span>
            </el-dialog>

            <!-- 详细信息 -->
            <div class="location-description">
                <h3>详细信息</h3>
                <p>{{ locationDetails.content }}</p>
            </div>
        </el-card>

        <!-- 地图部分 -->
        <div id="mapContainer">
            <!-- 切换视图按钮默认隐藏 -->
            <div id="toggleButton" class="hidden" @click="switchView">切换视图</div>
            <!-- 开始导航按钮默认可见 -->
            <button id="navigateButton" class="visible" @click="startNavigation">开始导航</button>
            <div id="map"></div>
        </div>
    </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { selectByNameService, LocationListService } from '@/api/location.js';
import { createReservationService } from '@/api/locationrecord.js';
import { ElMessage } from 'element-plus';

let map = null;
let is3DView = false;
let currentMarker = null;
export default {
    setup() {
        const route = useRoute();
        const router = useRouter();
        const locationName = ref(route.query.name);
        const locationId = ref(route.query.id);
        const locationDetails = ref({});
        const allLocations = ref([]);
        const recommendedLocations = ref([]);
        const showDialog = ref(false);
        const appointmentTime = ref('');
        const address = ref('');
        const fetchLocationDetails = async () => {
            try {
                const response = await selectByNameService(locationName.value);
                if (response && response.data && response.data.length) {
                    locationDetails.value = response.data[0];
                    address.value = locationDetails.value.address;
                } else {
                    ElMessage.error('未找到相关地点信息');
                }
            } catch (error) {
                ElMessage.error('获取地点信息失败，请稍后再试');
                console.error('Error fetching location details:', error);
            }
        };

        const fetchAllLocations = async () => {
            try {
                const response = await LocationListService({ page: 1, size: 10 });
                allLocations.value = response.data.list;
                getRecommendedLocations();
            } catch (error) {
                ElMessage.error('获取地点列表失败，请稍后再试');
                console.error('Error fetching all locations:', error);
            }
        };

        const getRecommendedLocations = () => {
            const sortedLocations = allLocations.value.sort((a, b) => b.number - a.number);
            recommendedLocations.value = sortedLocations.slice(0, 4);
        };

        const navTo = (path) => {
            router.push(path);
        };

        const bookLocation = () => {
            showDialog.value = true;
        };

        const confirmBooking = async () => {
            if (!appointmentTime.value) {
                ElMessage.warning('请选择预约时间');
                return;
            }

            const reservationData = {
                locationId: locationDetails.value.id,
                time: appointmentTime.value,
            };

            try {
                const response = await createReservationService(reservationData);
                ElMessage.success('预约成功！');
                console.log(response);
                showDialog.value = false;
            } catch (error) {
                console.error('Error creating reservation:', error);
            }
        };

        onMounted(async () => {
            try {
                await loadBaiduMapAPI();
                
                // 等待所有异步操作完成
                await Promise.all([fetchLocationDetails(), fetchAllLocations()]);
                
                initBaiduMap();
            } catch (error) {
                console.error('Failed to load Baidu Map API or fetch data:', error);
            }
        });

        watch(
            () => route.query,
            (newQuery) => {
                locationId.value = newQuery.id;
                locationName.value = newQuery.name;
                fetchLocationDetails();
            },
            { immediate: true }
        );

        return {
            locationId,
            locationName,
            locationDetails,
            recommendedLocations,
            navTo,
            bookLocation,
            confirmBooking,
            showDialog,
            appointmentTime,
            switchView,
            startNavigation,
        };
    },
};

const loadBaiduMapAPI = () => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = 'https://api.map.baidu.com/getscript?type=webgl&v=1.0&ak=02POhUIHozM8hKnOsu3nc7U0pc5iAcC2&services=&t=20241127202126';
        script.onload = () => {
            resolve();
        };
        script.onerror = (error) => {
            reject(error);
        };
        document.head.appendChild(script);
    });
};

const initBaiduMap = () => {
    map = new BMapGL.Map("map");
    initMap();
};

const initMap = () => {
    map.centerAndZoom('浙江师范大学', 12);
    map.enableScrollWheelZoom(true);
    var scaleControl = new BMapGL.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT });
    map.addControl(scaleControl);
    var zoomControl = new BMapGL.ZoomControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT });
    map.addControl(zoomControl);
};

const switchView = () => {
    if (is3DView) {
        map.setHeading(0);
        map.setTilt(0);
        map.setZoom(12);
        is3DView = false;
        document.getElementById("toggleButton").innerText = '切换到3D视图';
    } else {
        map.setHeading(64.5);
        map.setTilt(73);
        map.setZoom(19);
        is3DView = true;
        document.getElementById("toggleButton").innerText = '切换到2D视图';
    }
};

const startNavigation = () => {
    document.getElementById("navigateButton").classList.add("hidden");
    document.getElementById("toggleButton").classList.remove("hidden");

    var geolocation = new BMapGL.Geolocation();
    try {
        geolocation.getCurrentPosition(function(r) {
            if (r.point) {
                map.clearOverlays();
                currentMarker = new BMapGL.Marker(r.point);
                map.addOverlay(currentMarker);
                map.centerAndZoom(r.point, 16);

                var geoc = new BMapGL.Geocoder();
                geoc.getPoint("河北省石家庄市平山县迎宾路", function(point) {
                    if (point) {
                        var startPoint = r.point;
                        var endPoint = point;
                        navigate(startPoint, endPoint);
                    } else {
                        alert('无法找到终点的经纬度，请检查地址是否正确！');
                    }
                },"河北省石家庄市平山县迎宾路");
            } else {
                alert('无法获取当前位置，请检查您的设备设置。');
            }
        }, {enableHighAccuracy: true});
    } catch (err) {
        alert('该浏览器不支持获取地理位置。');
        console.log(err);
    }
};

function navigate(startPoint, endPoint) {
    var driving = new BMapGL.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
        onSearchComplete: function(results) {
            if (driving.getStatus() !== BMAP_STATUS_SUCCESS) {
                var statusMessage = getStatusMessage(driving.getStatus());
                alert('未找到合适的路线！状态码：' + driving.getStatus() + '，详细信息：' + statusMessage);
            }
        }
    });

    driving.search(startPoint, endPoint);
}

function getStatusMessage(statusCode) {
    switch (statusCode) {
        case BMAP_STATUS_SUCCESS:
            return "成功";
        case BMAP_STATUS_CITY_LIST:
            return "城市列表";
        case BMAP_STATUS_UNKNOWN_LOCATION:
            return "未知地点";
        case BMAP_STATUS_UNKNOWN_ROUTE:
            return "未知路线";
        case BMAP_STATUS_INVALID_REQUEST:
            return "无效请求";
        case BMAP_STATUS_PERMISSION_DENIED:
            return "权限被拒绝";
        case BMAP_STATUS_INVALID_RESPONSE:
            return "无效响应";
        case BMAP_STATUS_NOT_FOUND:
            return "未找到";
        case BMAP_STATUS_CITY_NOT_SUPPORT:
            return "城市不支持";
        case BMAP_STATUS_USER_CANCELED:
            return "用户取消";
        case BMAP_STATUS_NETWORK_ERROR:
            return "网络错误";
        case BMAP_STATUS_OVER_QUOTA:
            return "超出配额";
        default:
            return "未知错误";
    }
}
</script>

<style scoped>
.container {
    width: 70%;
    margin: 0 auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.breadcrumb-container {
    margin-bottom: 20px;
}

.main-card {
    padding: 20px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    background-color: #fff;
}

.content {
    display: flex;
    justify-content: space-between;
}

.location-detail {
    flex: 1;
    margin-right: 20px;
}

.image-card {
    margin-bottom: 20px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.location-image {
    width: 100%;
    height: auto;
    border-radius: 8px;
}

.location-info {
    margin-top: 10px;
}

.booking-section {
    margin-top: 20px;
    text-align: center;
}

.el-button {
    padding: 12px 24px;
    font-size: 16px;
    border-radius: 8px;
    transition: background-color 0.3s, transform 0.3s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.el-button:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.location-description {
    margin-top: 20px;
    padding: 20px;
    border-top: 1px solid #e4e7ed;
}

.recommendations {
    width: 300px;
}

.recommendation-list {
    display: flex;
    flex-direction: column;
}

.recommendation-item {
    margin-bottom: 30px;
}

.recommended-content {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 10px;
    border-radius: 5px;
    transition: background-color 0.3s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.recommended-content:hover {
    background-color: #f5f5f5;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.recommendation-image {
    width: 100px;
    height: 50px;
    object-fit: cover;
    margin-right: 10px;
    border-radius: 8px;
}

.recommendation-name {
    text-align: left;
}

#mapContainer {
    position: relative;
    width: 100%;
    height: 400px;
    margin-top: 20px;
    border: 2px solid #ccc;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

#map {
    width: 100%;
    height: 100%;
}

#toggleButton {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    background-color: white;
    border: 1px solid #ccc;
    padding: 5px 10px;
    cursor: pointer;
    border-radius: 4px;
    font-weight: bold;
    transition: background-color 0.3s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

#toggleButton:hover {
    background-color: #f0f0f0;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

#navigateButton {
    position: absolute;
    bottom: 10px;
    left: 10px;
    z-index: 1000;
    background-color: white;
    border: 1px solid #ccc;
    padding: 10px 20px;
    cursor: pointer;
    border-radius: 4px;
    font-weight: bold;
    transition: background-color 0.3s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

#navigateButton:hover {
    background-color: #f0f0f0;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.visible {
    display: block;
}

.hidden {
    display: none;
}

@media(max-width: 600px) {
    .image-card {
        width: 100%;
        margin-right: 0;
        margin-bottom: 20px;
    }

    .location-info {
        text-align: center;
    }

    .recommendation-item {
        flex-direction: column;
        align-items: center;
    }

    .recommendation-image {
        width: 100%;
        height: auto;
        margin-bottom: 10px;
    }

    #toggleButton, #navigateButton {
        width: calc(100% - 20px);
        text-align: center;
    }
}
</style>